<template>
  <div class="main">
    <el-card class="box-card">
      <el-divider content-position="left">第一步 题目上传</el-divider>
      <el-form ref="problemForm" :model="formData">
        <el-form-item label="题目">
          <el-input v-model="formData.title"></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <el-button @click="openDialog">选择标签</el-button>
          <el-divider content-position="left">已选择的标签</el-divider>
          <div v-if="selectedTags.length">
            <el-tag
                v-for="tag in selectedTags"
                :key="tag.id"
                closable
                @close="toggleTag(tag)"
                class="selected-tag">
              {{ tag.tag }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="难度">
          <el-rate v-model="formData.difficulty" :max="5"></el-rate>
        </el-form-item>
        <el-form-item label="题目描述">
          <el-input
              type="textarea"
              v-model="formData.description"
              :rows="4">
          </el-input>
        </el-form-item>
        <el-button size="large" type="primary" @click="submitForm">下一步</el-button>
      </el-form>
    </el-card>

    <el-dialog
        title="选择标签"
        v-model="showTagDialog"
        class="dialog-main"
        width="500px">
      <div v-if="loading">加载中...</div>
      <div v-else v-for="(tagType, index) in uniqueTagTypes" :key="index">
        <h3>{{ tagType }}</h3>
        <div class="tag-container">
          <el-checkbox-group v-model="selectedTags" class="custom-checkbox-group">
            <el-checkbox
                v-for="tag in tags.filter(t => t.tagType === tagType)"
                :label="tag.tag"
                :key="tag.id"
                :value="tag"
                class="custom-checkbox">
              {{ tag.tag }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from "@/router";
import {useStore} from "vuex";

const formData = ref({
  title: "",
  difficulty: 0,
  description: "",
  tags: []
});

const tags = ref([]);
const selectedTags = ref([]);
const showTagDialog = ref(false);
const uniqueTagTypes = computed(() => [...new Set(tags.value.map(tag => tag.tagType))]);
const loading = ref(false);
const store = useStore();
const fetchTags = async () => {
  loading.value = true;
  const response = await axios.get(`/oj/ProblemsGroup/tag`, {
    headers: { 'Content-Type': 'application/json', },
    params: { query: 'all' }
  });

  if (response.data.code === 200) {
    tags.value = response.data.data;
  } else {
    ElMessage.error('Failed to load tags');
  }
  loading.value = false;
};

const toggleTag = (tag) => {
  const index = selectedTags.value.findIndex(t => t.id === tag.id);
  if (index === -1) {
    selectedTags.value.push(tag);
  } else {
    selectedTags.value.splice(index, 1);
  }
};

const submitForm = async () => {
  formData.value.tags = selectedTags.value.map(tag => tag.tag);
  try {
    const response = await axios.post(`/oj/ProblemsGroup/problems/uploadProblems`, formData.value, {
      headers: {'Content-Type': 'application/json',}
    });
    if (response.data.code === 200) {
      ElMessage.success("题目上传完成");

      await store.dispatch('updateProblemId', response.data.data.id);
      router.push("/student/oj/UploadTestGroup");
    } else {
      ElMessage.error(`Failed to complete Step 1: ${response.data.msg}`);
    }
  } catch (error) {
    ElMessage.error('Error submitting form');
  }
};

const openDialog = () => {
  showTagDialog.value = true;
};

const closeDialog = () => {
  showTagDialog.value = false;
};

onMounted(fetchTags);
</script>

<style scoped>
.main {
  width: 100%;
  height: 100%;
  margin: 2.5vh auto;
}
.box-card {
  margin-bottom: 20px;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
}

.selected-tag {
  margin-right: 5px;
  margin-top: 5px;
}

.custom-checkbox-group .el-checkbox {
  margin-right: 10px;
}

.custom-dialog .dig-button {
  display: flex;
  justify-content: space-between;
}
</style>
